package yxy.cherry.paycenter.servlet.channel.shengye;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import yxy.apple.logger.Logger;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.charge;
import yxy.cherry.game.base.bean.SDKParm;
import yxy.cherry.game.base.bean.SdkParmEnum;
import yxy.cherry.paycenter.channelmodule.ActType;
import yxy.cherry.paycenter.channelmodule.sdk_shengye.PayMoudle_shengye;
import yxy.cherry.paycenter.database.dao.ordersDao;
import yxy.cherry.paycenter.database.db.orders;
import yxy.cherry.paycenter.servlet.channel.Servlet;
import yxy.cherry.paycenter.util.HttpUtil;
import yxy.cherry.paycenter.util.SdkUtil;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.channel.SdkChannel;
import yxy.game.pm2.bean.module.OrderInfoModule;

/**
 * 盛也 - 支付回调
 * @author Dell
 *
 */
public class Servlet_ShengYe extends Servlet {

	private static final Logger logger = Logger.create(Servlet_ShengYe.class);
	
	//处理支付回调返回结果
	private static final String success = "success’";	//交易结果 成功
	private static final String fail = "fail";	//交易结果 失败
	
	@Override
	public String getUrl() {
		return "/sdk_" + getChannel(); // + PayMoudle_weixin.android;
	}
	
	public Servlet_ShengYe() {
//		SdkService.getInstance().addServlet("/jh", new Servlet_jh());
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String data = HttpUtil.getPostData(req);
		JSONObject info = getData(data);
	
//		JSONObject info = HttpUtil.getHeaderData(req);
//		logger.info("Servlet_ShengYe info :" + info);
		
//		参数名 	类型 	说明
//		orderid string 	订单号
//		openid 	string 	⽤户openid, 唯⼀表⽰
//		price 	int 	价格（单位：元）
//		item_id int 	类别id
//		other 	string 	额外参数1 ⽤”&”符号拼接下单时的额外参数1(extends_param1)和参数	2(extends_param2)
//		sign 	string 	签名 （具体参考签名说明）
		
		String orderid = info.getString("orderid");
		String openid = info.getString("openid");
		String price = info.getString("price");
		String other = info.getString("other");
		String sign = info.getString("sign");
	
		String newsign = getSign(info);
		
		if(!newsign.equals(sign)) {
			returnInfo(fail, resp);
			return;
		}

		orders o = ordersDao.getOrderByMyorderid(orderid);
		if(o == null) {
			returnInfo(fail, resp);
			return;
		}
		
		if(o.getOrderstate() == OrderInfoModule.orderinfofinish) {
			returnInfo(success, resp);
			return;
		}
		
		int paymount = (int)(Double.valueOf(price) * 100);
		
		o.setUpdatetime(new Date());
		o.setSubchannel(o.getChannel());
		o.setOrderstate(OrderInfoModule.orderinfofinish);
		o.setPayamount(paymount);
		ordersDao.update(o);
		
		ActType at = ActType.getat(o.getActtype());
		PayMoudle_shengye am = new PayMoudle_shengye();
		ArrayList<Currency> curs = am.getRewardInfoByType(o.getPlayercode(), at, o.getGoodsid());
		charge charge = DataCenter.getData(o.getGoodsid(), charge.class);
		am.createOrderInfoModule(o, curs, charge.getVipexp(), o.getGoodsprice());
	
		returnInfo(success, resp);
	}



	/**
	 * 返回信息到渠道
	 * 
	 * @param data
	 * @param resp
	 */
	public void returnInfo(String data, HttpServletResponse resp) {
		PrintWriter pw = null;
		resp.addHeader("Access-Control-Allow-Origin", "*");

		try {
			pw = resp.getWriter();
			pw.write(data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pw != null)
				pw.close();
		}
	}

	@Override
	public String getChannel() {
		return SdkChannel.sdk_shengye;
	}
	
	
	public static String getSign(JSONObject info) {
//		（1）在参数列表中，除去sign字段，⽆特殊说明都是需参与签名⽣成的字段。为空的字段请设置为
//		0或空字符串”，不要设置为null（会导致签名错误）。
//		（2）将参与⽣成签名的参数的key按照字典升序排序（使⽤ksort函数）， 然后把key=value ⽤&连
//		接组成字符串，得到待签名字符串。
//		（3）在步骤2得到待签名的字符串后直接拼接appsecret 得到签名字符串。盛也提供，建议不要暴
//		露到前端。
//		（4）对签名字符串进⾏md5加密后转成⼩写得到签名。
		
//		数名 类型 说明
//		channel string 我⽅提供的⼩游戏key，可暴露在前端
//		appsecret string 我⽅提供，⽤于⽀付相关操作，建议不要暴露到前端
//		openId string ⽤户openid，唯⼀标识
		
//		String appsecret = "N1ERGDW2VV7GTPONH0SCRBI91U3NDBO2";
		
		String appsecret = SDKParm.getSdkparmvalue(SdkParmEnum.shengye_appsecret);
		String newsign = SdkUtil.getSignData(info, appsecret).toLowerCase();
		return newsign;
	}
	
	
	public static JSONObject getData(String str) {

		long start = System.currentTimeMillis();
		
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
        /*   \n 回车(\u000a)   \t 水平制表符(\u0009)   \s 空格(\u0008)   \r 换行(\u000d)   */
		Matcher m = p.matcher(str);
		String string = m.replaceAll("");

		String[] strs = string.split("----------------");

		JSONObject json = new JSONObject();
		for (int i = 0; i < strs.length; i++) {
			if (strs[i].contains(";")) {
				String[] strs2 = strs[i].split("name");
				for(String s : strs2) {
					if(s.contains("=")) {
						String[] parvaules = s.split("\\\""); 
						json.put(parvaules[1], parvaules[2]);
					}
				}
	
			}
		}

		long time = System.currentTimeMillis() - start;
		logger.info("json: " + json + " " + time);
		return json;
	}
	
}
